import {Component, OnInit, ViewChild} from '@angular/core';
import {Events, ModalController, NavController, ToastController} from '@ionic/angular';
import {ActivatedRoute} from '@angular/router';
import {HttpService} from '../../services/http.service';
import {BasePage} from '../../common/basePage';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {AppConfig} from '../../common/app-config.enum';
import {IframePageComponent} from '../../components/iframe-page/iframe-page.component';
import {ActionPanelComponent} from '../../components/action-panel/action-panel.component';
import {Storage} from '@ionic/storage';

/**
 * 提现
 */
@Component({
  selector: 'app-user-cash-withdrawal',
  templateUrl: './user-cash-withdrawal.page.html',
  styleUrls: ['./user-cash-withdrawal.page.scss'],
})
export class UserCashWithdrawalPage extends BasePage implements OnInit {

  userRole: number;
  userType: number;
  withdrawalOpt: any = {};
  maxWithdraw = 0; // 最大提现金额
  policy = 'T1'; // 当日次日到账选择，默认为次日
  amount: any = null; // 提现金额
  fee: number = null; // 手续费
  errMsg = ''; // 错误信息
  isShowBankArea = false; // 是否显示开户行所在地
  // 获取开户行所在地组件实例
  @ViewChild('bankAreaPanel') bankAreaPanel: ActionPanelComponent;
  city: any = null; // 开户行所在地信息(包含省份和城市编号和名称)

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController,
              private storage: Storage,
              private modalCtrl: ModalController,
              private events: Events,
              private routeInfo: ActivatedRoute,
              private service$: HttpService
  ) {
    super(navCtrl, toastCtrl);
  }

  ngOnInit() {
    this.getData();
  }

  // 提现准备
  getData() {
    this.storage.get(AppConfig.USER_INFO)
      .then(userInfo => {
        this.userRole = userInfo[AppConfig.USER_ROLE_KEY]; // 获取用户角色(出借人、借款人)
        this.userType = userInfo[AppConfig.USER_TYPE_KEY]; // 获取用户类型(企业、个人)
        this.isShowBankArea = (this.userType === 2);
        this.service$.doRequest(UrlAndOPT.auth_withdrawal_pre, {userRole: this.userRole})
          .subscribe(obj => {
            if (obj) {
              this.withdrawalOpt = obj;
              this.fee = this.withdrawalOpt['withdrawFeeMin'] * 1;
              this.maxWithdraw = Math.min(this.withdrawalOpt['maxWithdraw'] * 1, this.withdrawalOpt['balance']);
            }
          });
      });
  }

  // 当时次日到账切换
  // togglePolicy() {
  //   if (this.policy === 'T0' && !!this.amount) {
  //     const fee = Math.floor(
  //       (this.amount - this.withdrawalOpt['withdrawFeePoint'] * 1) * (this.withdrawalOpt['withdrawFeeRate'] * 1)
  //       ) / 100
  //       + this.withdrawalOpt['withdrawFeeMin'] * 1; // 当日到账手续费 = (提现金额 - 起征点) * 费率 + 每笔最低手续费
  //     this.fee = Math.max(fee, this.withdrawalOpt['withdrawFeeMin'] * 1);
  //   } else {
  //     this.fee = this.withdrawalOpt['withdrawFeeMin'] * 1; // 次日到账手续费为每笔最低手续费(固定值)
  //   }
  // }

  // 限制输入：最多保留两位小数，如果超出金额限制显示相关提示信息
  limitValue($event) {
    if (this.amount) {
      $event.target.value = Math.floor($event.target.value * 100) / 100;
      // 计算手续费
      // this.togglePolicy();
      // 如果为个人用户，根据输入金额控制显示开户行所在地
      if (this.userType === 1) {
        this.isShowBankArea = !(this.amount < 50000);
        if (!this.isShowBankArea) {
          this.city = null; // 当地域关闭时，将所选城市置空
        }
      }
    } else {
      this.amount = null;
    }
    // 超过限定金额时，显示上下限额提示
    if (!this.amount || this.amount < this.withdrawalOpt['minWithdraw']) {
      this.errMsg = '最低提现金额 ' + this.withdrawalOpt['minWithdraw'] + '元';
    } else if (this.amount > this.maxWithdraw) {
      this.errMsg = '最高提现金额 ' + this.maxWithdraw + '元';
    } else {
      this.errMsg = '';
    }
  }

  // 打开开户行所在地组件
  openArea() {
    this.bankAreaPanel.showActionPanel();
  }

  // 关闭开户行所在地组件
  closeBankArea(city) {
    // 未选择任何城市时，将城市置空
    if (!!city) {
      this.city = city;
    }
    this.bankAreaPanel.hideActionPanel();
  }

  // 前往银行提现页面
  async doWithdrawal() {
    if (this.amount && !this.errMsg) {
      let params: any = {
        amount: this.amount,
        fee: this.fee,
        policy: this.policy
      };
      if (this.isShowBankArea) {
        if (!this.city) {
          this.showToast('请选择开户行所在地');
          return false;
        } else {
          params = {
            ...params,
            provNum: this.city['prov_num'],
            cityNum: this.city['city_num']
          };
        }
      }
      this.service$.doRequest(UrlAndOPT.user_withdrawal, params)
        .subscribe(async (obj) => {
          if (obj) {
            // 打开提现model
            const modal = await this.modalCtrl.create({
              component: IframePageComponent,
              componentProps: {
                title: '提现',
                url: obj['url']
              }
            });
            await modal.present();
            // 关闭model后，发送用户账户变动通知，关闭提现页面
            await modal.onDidDismiss();
            this.events.publish(AppConfig.TOPIC_USER_FUNC);
            this.navCtrl.navigateBack(['/tabs/user']);
          }
        });
    }
  }

}
